package com.atguigu.juc.atomics;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicMarkableReference;

/**
 * @author yanglin
 * @create 2024-01-26 15:37 星期五
 * description:
 */
public class AtomicMarkableReferenceDemo {

    static AtomicMarkableReference atomicMarkableReference = new AtomicMarkableReference(100,false);
    
    public static void main(String[] args) {
        new Thread(() -> {
            //获取标记位
            boolean marked = atomicMarkableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + "\t 默认标识：" + marked);
            //暂停1s，确保t2线程拿到是同样的标识
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean b = atomicMarkableReference.compareAndSet(100, 1000, marked, !marked);
            System.out.println("t1线程是否修改成功：" + b);
            
        },"t1").start();
        
        new Thread(() -> {
            boolean marked = atomicMarkableReference.isMarked();
            System.out.println(Thread.currentThread().getName() + "\t 默认标识：" + marked);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "\t 当前的标记为：" + atomicMarkableReference.isMarked());
            boolean b = atomicMarkableReference.compareAndSet(100, 2000, marked, !marked);
            System.out.println("t2线程是否修改成功：" + b);
        },"t2").start();
    }
    
}
